#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void Swap(int* p1, int* p2)
{
	int k = *p1;
	*p1 = *p2;
	*p2 = k;
}

void InsertSort(int* p, int n)
{
	for (int i = 0; i < n - 1; i++)
	{
		int end = i;
		int gap = p[end + 1];
		while (end >= 0)
		{
			if (p[end] > gap)
			{
				p[end + 1] = p[end];
				end--;
			}
			else
			{
				break;
			}
		}
		p[end + 1] = gap;
	}
}

void ShellSort(int* p, int n)
{
	int gap = n;
	while (gap > 1)
	{
		gap /= 2;
		for (int i = 0; i < n - gap; i++)
		{
			int end = i;
			int tmp = p[end + gap];
			while (end > 0)
			{
				if (p[end] > tmp)
				{
					p[end + gap] = p[end];
					end -= gap;
				}
				else
				{
					break;
				}
			}
			p[end + gap] = tmp;
		}
	}
}

void BubbleSort(int* p, int n)
{
	for (int i = 0; i < n - 1; i++)
	{
		for (int k = 0; k < n - 1 - i; k++)
		{
			if (p[n] > p[n + 1])
			{
				Swap(&p[n], &p[n + 1]);
			}
		}
	}
}

void AdjustDoen(int* p, int n, int root)
{
	int parent = root;
	int child = 2 * parent + 1;
	while (child < n)
	{
		if (child + 1 < n && p[child] < p[child + 1])
		{
			child++;
		}
		if (p[parent] < p[child])
		{
			Swap(&p[child], &p[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapSort(int* p, int n)
{
	for (int i = (n - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDoen(p, n, i);
	}
	int end = n - 1;
	while (end)
	{
		Swap(&p[0], &p[end]);
		AdjustDoen(p, end, 0);
		end--;
	}
}